package src

import (
	"bytes"
	_ "embed"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

//go:embed Dockerfile
var dockerfileContent string

func GetImageName(config *Config) string {
	return fmt.Sprintf("%s/zhongba/%s:%s", config.Domain, config.Module, config.Version)
}

func GetBuildArgs(config *Config) map[string]string {
	path := config.GetJarFilePath()
	name := config.getJarFileName()
	buildArgs := map[string]string{
		"JAR_PATH": path,
		"JAR_NAME": name,
	}
	return buildArgs
}

func BuildDocker(config *Config) error {
	err := BuildDockerImage(config)
	if err != nil {
		fmt.Printf("构建镜像失败: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("镜像构建成功推送中...")
	err = PushDockerImage(config)
	if err != nil {
		fmt.Printf("推送镜像失败: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("镜像推送成功")
	return nil
}

func BuildDockerImage(config *Config) error {
	ImageName := GetImageName(config)
	buildArgs := GetBuildArgs(config)
	cmdArgs := []string{"build", "-t", ImageName, "-f", "-", "."}
	for key, value := range buildArgs {
		cmdArgs = append(cmdArgs, "--build-arg", key+"="+value)
	}
	fmt.Printf("执行命令: docker %v\n", strings.Join(cmdArgs, " "))
	cmd := exec.Command("docker", cmdArgs...)
	cmd.Dir = config.GetContextPath()
	cmd.Stdin = bytes.NewBufferString(dockerfileContent)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func PushDockerImage(config *Config) error {
	ImageName := GetImageName(config)
	fullImageName := fmt.Sprintf("%s", ImageName)
	cmd := exec.Command("docker", "push", fullImageName)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}
